package com.joker.web.controller.orange;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.joker.common.core.controller.BaseController;
import com.joker.common.core.domain.PageQuery;
import com.joker.common.core.domain.R;
import com.joker.common.core.page.TableDataInfo;
import com.joker.common.helper.LoginHelper;
import com.joker.orange.domain.*;
import com.joker.orange.domain.bo.*;
import com.joker.orange.domain.vo.*;
import com.joker.orange.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/pixiv")
public class AppPixivController extends BaseController {

    private final INovelCategoryService novelCategoryService;
    private final INovelInfoService novelInfoService;
    private final INovelChapterService novelChapterService;

    private final ICaricatureCategoryService caricatureCategoryService;
    private final ICaricatureInfoService caricatureInfoService;
    private final ICaricatureChapterService caricatureChapterService;

    private final IAnimeCategoryService animeCategoryService;
    private final IVideoInfoService videoInfoService;

    private final ICarouselImagesService carouselImagesService;
    private final IAdvertisingSpaceService advertisingSpaceService;

    private final IBuyOrderService buyOrderService;
    private final ICollectionService collectionService;
    private final IUserLikeService userLikeService;

    private final IUserInfoService userInfoService;

    /**
     * 二次元首页
     * pixivType 0-漫画、1-小说、2-动漫
     */
    @PostMapping("/queryPixixIndexInfo")
    public R<Map<String, Object>> queryPixixIndexInfo(@RequestBody Map<String, String> params) {
        if (!params.containsKey("pixivType")) {
            return R.fail("二次元类型不能为空！");
        }
        Map<String, Object> result = new HashMap<>();
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(1);
        pageQuery.setPageSize(6);
        // 广告
        AdvertisingSpaceBo advertisingSpaceBo = new AdvertisingSpaceBo();
        advertisingSpaceBo.setIsDisplay("0");

        // 轮播图列表
        CarouselImagesBo imagesBo = new CarouselImagesBo();
        imagesBo.setIsDisplay("0");

        if ("0".equals(params.get("pixivType"))) {
            imagesBo.setCarouselType("2");
            advertisingSpaceBo.setAdvertisingType("2");
        } else if ("1".equals(params.get("pixivType"))) {
            imagesBo.setCarouselType("3");
            advertisingSpaceBo.setAdvertisingType("3");
        } else {
            imagesBo.setCarouselType("4");
            advertisingSpaceBo.setAdvertisingType("4");
        }

        List<CarouselImagesVo> imagesList = carouselImagesService.queryList(imagesBo);
        result.put("imagesList", imagesList);

        List<AdvertisingSpaceVo> advertisingList = advertisingSpaceService.queryList(advertisingSpaceBo);
        result.put("advertisingList", advertisingList);
        if ("0".equals(params.get("pixivType"))) {
            // 漫画分类
            CaricatureCategoryBo caricatureCategoryBo = new CaricatureCategoryBo();
            caricatureCategoryBo.setVisible("0");
            List<CaricatureCategoryVo> categoryList = caricatureCategoryService.queryList(caricatureCategoryBo);
            result.put("categoryList", categoryList);
            // 漫画推荐
            CaricatureInfoBo caricatureInfoBo = new CaricatureInfoBo();
            caricatureInfoBo.setIsTop("0");
            TableDataInfo<CaricatureInfoVo> dataInfo = caricatureInfoService.queryPageList(caricatureInfoBo, pageQuery);
            result.put("dataList", dataInfo.getRows());
        } else if ("1".equals(params.get("pixivType"))) {
            // 小说分类
            NovelCategoryBo novelCategoryBo = new NovelCategoryBo();
            novelCategoryBo.setVisible("0");
            List<NovelCategoryVo> categoryList = novelCategoryService.queryList(novelCategoryBo);
            result.put("categoryList", categoryList);
            // 小说推荐
            NovelInfoBo novelInfoBo = new NovelInfoBo();
            novelInfoBo.setIsTop("0");
            TableDataInfo<NovelInfoVo> dataInfo = novelInfoService.queryPageList(novelInfoBo, pageQuery);
            result.put("dataList", dataInfo.getRows());
        } else {
            // 动漫分类
            AnimeCategoryBo animeCategoryBo = new AnimeCategoryBo();
            animeCategoryBo.setVisible("0");
            List<AnimeCategoryVo> categoryList = animeCategoryService.queryList(animeCategoryBo);
            result.put("categoryList", categoryList);
            // 动漫推荐
            VideoInfoBo videoInfoBo = new VideoInfoBo();
            videoInfoBo.setVideoType("2");
            videoInfoBo.setIsTop("0");
            TableDataInfo<VideoInfoVo> dataInfo = videoInfoService.queryPageList(videoInfoBo, pageQuery);
            result.put("dataList", dataInfo.getRows());
        }
        return R.ok(result);
    }

    /**
     * 小说查看更多
     * pageNum 当前页数
     * pageSize 每页条数
     * categoryId 分类ID（可传可不传）
     */
    @PostMapping("/selectMoreNovelList")
    public TableDataInfo<NovelInfoVo> selectMoreNovelList(@RequestBody JSONObject jsonObject) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(jsonObject.getInt("pageNum"));
        pageQuery.setPageSize(jsonObject.getInt("pageSize"));
        NovelInfoBo novelInfoBo = new NovelInfoBo();
        if (jsonObject.containsKey("categoryId") && ObjectUtil.isNotEmpty(jsonObject.get("categoryId"))) {
            novelInfoBo.setCategoryId(jsonObject.getLong("categoryId"));
        }
        return novelInfoService.queryPageList(novelInfoBo, pageQuery);
    }

    /**
     * 小说换一批
     */
    @PostMapping("/novelChangeBatchList")
    public R<List<NovelInfoVo>> novelChangeBatchList(@RequestBody JSONObject jsonObject) {
        NovelInfoBo novelInfoBo = new NovelInfoBo();
        if (jsonObject.containsKey("categoryId") && ObjectUtil.isNotEmpty(jsonObject.get("categoryId"))) {
            novelInfoBo.setCategoryId(jsonObject.getLong("categoryId"));
        }
        List<NovelInfoVo> novelInfoVoList = novelInfoService.queryList(novelInfoBo);
        return R.ok(novelInfoService.getRandomNovels(novelInfoVoList, 6));
    }

    /**
     * 漫画换一批
     */
    @PostMapping("/caricatureChangeBatchList")
    public R<List<CaricatureInfoVo>> caricatureChangeBatchList(@RequestBody JSONObject jsonObject) {
        CaricatureInfoBo caricatureInfoBo = new CaricatureInfoBo();
        if (jsonObject.containsKey("categoryId") && ObjectUtil.isNotEmpty(jsonObject.get("categoryId"))) {
            caricatureInfoBo.setCategoryId(jsonObject.getLong("categoryId"));
        }
        List<CaricatureInfoVo> caricatureCategoryVoList = caricatureInfoService.queryList(caricatureInfoBo);
        return R.ok(caricatureInfoService.getRandomCaricatures(caricatureCategoryVoList, 6));
    }

    /**
     * 漫画查看更多
     * pageNum 当前页数
     * pageSize 每页条数
     * categoryId 分类ID（可传可不传）
     */
    @PostMapping("/selectMoreCaricatureList")
    public TableDataInfo<CaricatureInfoVo> selectMoreCaricatureList(@RequestBody JSONObject jsonObject) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(jsonObject.getInt("pageNum"));
        pageQuery.setPageSize(jsonObject.getInt("pageSize"));
        CaricatureInfoBo caricatureInfoBo = new CaricatureInfoBo();
        if (jsonObject.containsKey("categoryId") && ObjectUtil.isNotEmpty(jsonObject.get("categoryId"))) {
            caricatureInfoBo.setCategoryId(jsonObject.getLong("categoryId"));
        }
        return caricatureInfoService.queryPageList(caricatureInfoBo, pageQuery);
    }

    /**
     * 动漫查看更多
     * pageNum 当前页数
     * pageSize 每页条数
     * categoryId 分类ID（可传可不传）
     */
    @PostMapping("/selectMoreAnimeList")
    public TableDataInfo<VideoInfoVo> selectMoreAnimeList(@RequestBody JSONObject jsonObject) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(jsonObject.getInt("pageNum"));
        pageQuery.setPageSize(jsonObject.getInt("pageSize"));
        VideoInfoBo videoInfoBo = new VideoInfoBo();
        videoInfoBo.setVideoType("2");
        if (jsonObject.containsKey("categoryId") && ObjectUtil.isNotEmpty(jsonObject.get("categoryId"))) {
            videoInfoBo.setCategoryId(jsonObject.getLong("categoryId"));
        }
        return videoInfoService.queryPageList(videoInfoBo, pageQuery);
    }

    /**
     * 动漫换一批
     */
    @PostMapping("/animeChangeBatchList")
    public R<List<VideoInfoVo>> changeBatchList(@RequestBody JSONObject jsonObject) {
        VideoInfoBo videoInfoBo = new VideoInfoBo();
        videoInfoBo.setVideoType("2");
        if (jsonObject.containsKey("categoryId") && ObjectUtil.isNotEmpty(jsonObject.get("categoryId"))) {
            videoInfoBo.setCategoryId(jsonObject.getLong("categoryId"));
        }
        List<VideoInfoVo> videoInfoList = videoInfoService.queryList(videoInfoBo);
        return R.ok(videoInfoService.getRandomVideos(videoInfoList, 6));
    }

    /**
     * 小说详情
     * novelId 小说id
     * pageSize 分页大小
     * pageNum 当前页数
     */
    @PostMapping("/queryNovelById")
    public R<Map<String, Object>> queryNovelById(@RequestBody Map<String, Object> map) {
        log.info("【queryNovelById】小说详情入参：{}", JSONUtil.parse(map));
        if (!map.containsKey("novelId") || ObjectUtil.isEmpty(map.get("novelId"))) {
            return R.fail("小说ID不能为空！");
        }
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(Integer.valueOf(map.get("pageNum").toString()));
        pageQuery.setPageSize(Integer.valueOf(map.get("pageSize").toString()));

        Map<String, Object> result = new HashMap<>();
        NovelInfoVo novelInfoVo = novelInfoService.queryById(Long.valueOf(map.get("novelId").toString()));

        // 判断是否点赞和收藏
        CollectionInfo collectionInfo = new CollectionInfo();
        collectionInfo.setCollectionId(novelInfoVo.getId());
        collectionInfo.setUserId(LoginHelper.getUserId());
        collectionInfo.setCollectionType("2");
        CollectionInfo collection = collectionService.selectCollection(collectionInfo);
        if (ObjectUtil.isNotNull(collection)) {
            novelInfoVo.setIsCollection("0");
        } else {
            novelInfoVo.setIsCollection("1");
        }
        UserLikeBo userLikeBo = new UserLikeBo();
        userLikeBo.setUserId(LoginHelper.getUserId());
        userLikeBo.setLikeTypeId(novelInfoVo.getId());
        userLikeBo.setLikeType("2");
        UserLikeVo userLikeList = userLikeService.queryUserLikeVo(userLikeBo);
        if (ObjectUtil.isNotNull(userLikeList)) {
            novelInfoVo.setIsGiveLike("0");
        } else {
            novelInfoVo.setIsGiveLike("1");
        }

        result.put("novelInfo", novelInfoVo);

        // 小说目录
        NovelChapterBo novelChapterBo = new NovelChapterBo();
        novelChapterBo.setNovelId(novelInfoVo.getId());
        TableDataInfo<NovelChapterVo> chapterList = novelChapterService.queryPageList(novelChapterBo, pageQuery);
        for (NovelChapterVo row : chapterList.getRows()) {
            BuyOrder buyOrder = buyOrderService.queryByProductId(novelInfoVo.getId(), row.getId(), "2");
            if (ObjectUtil.isNotNull(buyOrder)) {
                row.setIsBuy("0");
            } else {
                row.setIsBuy("1");
            }
        }
        result.put("chapterList", chapterList.getRows());
        result.put("total", chapterList.getTotal());

        return R.ok(result);
    }

    /**
     * 漫画详情
     * caricatureId 漫画id
     * pageSize 分页大小
     * pageNum 当前页数
     */
    @PostMapping("/queryCaricatureById")
    public R<Map<String, Object>> queryCaricatureById(@RequestBody Map<String, Object> map) {
        log.info("【queryCaricatureById】漫画详情入参：{}", JSONUtil.parse(map));
        if (!map.containsKey("caricatureId") || ObjectUtil.isEmpty(map.get("caricatureId"))) {
            return R.fail("漫画ID不能为空！");
        }
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(Integer.valueOf(map.get("pageNum").toString()));
        pageQuery.setPageSize(Integer.valueOf(map.get("pageSize").toString()));

        Map<String, Object> result = new HashMap<>();
        CaricatureInfoVo caricatureInfoVo = caricatureInfoService.queryById(Long.valueOf(map.get("caricatureId").toString()));

        // 判断是否点赞和收藏
        CollectionInfo collectionInfo = new CollectionInfo();
        collectionInfo.setCollectionId(caricatureInfoVo.getId());
        collectionInfo.setUserId(LoginHelper.getUserId());
        collectionInfo.setCollectionType("3");
        CollectionInfo collection = collectionService.selectCollection(collectionInfo);
        if (ObjectUtil.isNotNull(collection)) {
            caricatureInfoVo.setIsCollection("0");
        } else {
            caricatureInfoVo.setIsCollection("1");
        }
        UserLikeBo userLikeBo = new UserLikeBo();
        userLikeBo.setUserId(LoginHelper.getUserId());
        userLikeBo.setLikeTypeId(caricatureInfoVo.getId());
        userLikeBo.setLikeType("3");
        UserLikeVo userLikeList = userLikeService.queryUserLikeVo(userLikeBo);
        if (ObjectUtil.isNotNull(userLikeList)) {
            caricatureInfoVo.setIsGiveLike("0");
        } else {
            caricatureInfoVo.setIsGiveLike("1");
        }

        result.put("caricatureInfo", caricatureInfoVo);

        // 漫画目录
        CaricatureChapterBo caricatureChapterBo = new CaricatureChapterBo();
        caricatureChapterBo.setCaricatureId(caricatureInfoVo.getId());
        TableDataInfo<CaricatureChapterVo> chapterList = caricatureChapterService.queryPageList(caricatureChapterBo, pageQuery);

        for (CaricatureChapterVo row : chapterList.getRows()) {
            BuyOrder buyOrder = buyOrderService.queryByProductId(caricatureInfoVo.getId(), row.getId(), "3");
            if (ObjectUtil.isNotNull(buyOrder)) {
                row.setIsBuy("0");
            } else {
                row.setIsBuy("1");
            }
        }

        result.put("chapterList", chapterList.getRows());
        result.put("total", chapterList.getTotal());

        return R.ok(result);
    }

    /**
     * 开始阅读
     * chapterId 章节ID
     * pixivType 0-漫画、1-小说
     */
    @PostMapping("/startReading")
    public R<Map<String, Object>> startReading(@RequestBody JSONObject map) {
        Map<String, Object> result = new HashMap<>();
        if (!map.containsKey("chapterId") || ObjectUtil.isEmpty(map.get("chapterId"))) {
            return R.fail("章节ID不能为空！");
        }
        if (!map.containsKey("pixivType") || ObjectUtil.isEmpty(map.get("pixivType"))) {
            return R.fail("类型不能为空！");
        }
        if ("0".equals(map.get("pixivType"))) {
            NovelChapterVo novelChapterVo = novelChapterService.queryById(map.getLong("chapterId"));
            if (novelChapterVo == null) {
                return R.fail("章节不存在");
            }
            result = getNovelChapter(novelChapterVo);
        } else {
            CaricatureChapterVo caricatureChapterVo = caricatureChapterService.queryById(map.getLong("chapterId"));
            if (caricatureChapterVo == null) {
                return R.fail("章节不存在");
            }
            result = getCaricatureChapter(caricatureChapterVo);
        }
        return R.ok(result);
    }

    /**
     * 小说/漫画查询下一章节
     * chapterId 章节ID
     * pixivType 0-漫画、1-小说
     */
    @PostMapping("/selectNextChapterById")
    public R<Map<String, Object>> selectNextChapterById(@RequestBody JSONObject jsonObject) {
        Map<String, Object> result = new HashMap<>();
        if (!jsonObject.containsKey("chapterId") || ObjectUtil.isEmpty(jsonObject.get("chapterId"))) {
            return R.fail("章节ID不能为空！");
        }
        if (!jsonObject.containsKey("pixivType") || ObjectUtil.isEmpty(jsonObject.get("pixivType"))) {
            return R.fail("类型不能为空！");
        }
        if ("0".equals(jsonObject.get("pixivType"))) {
            NovelChapterVo vo = novelChapterService.queryById(jsonObject.getLong("chapterId"));
            NovelChapterBo bo = new NovelChapterBo();
            bo.setId(vo.getId());
            bo.setNovelId(vo.getNovelId());
            NovelChapterVo novelChapter = novelChapterService.selectNextChapterById(bo);
            if (novelChapter == null) {
                return R.fail("已到了最后章节");
            }
            result = getNovelChapter(novelChapter);
        } else {
            CaricatureChapterVo vo = caricatureChapterService.queryById(jsonObject.getLong("chapterId"));
            CaricatureChapterBo bo = new CaricatureChapterBo();
            bo.setId(vo.getId());
            bo.setCaricatureId(vo.getCaricatureId());
            CaricatureChapterVo caricatureChapter = caricatureChapterService.selectNextChapterById(bo);
            if (caricatureChapter == null) {
                return R.fail("已到了最后章节");
            }
            result = getCaricatureChapter(caricatureChapter);
        }
        return R.ok(result);
    }

    /**
     * 小说/漫画查询上一章节
     * chapterId 章节ID
     * pixivType 0-漫画、1-小说
     */
    @PostMapping("/selectLastChapterById")
    public R<Map<String, Object>> selectLastChapterById(@RequestBody JSONObject jsonObject) {
        Map<String, Object> result = new HashMap<>();
        if (!jsonObject.containsKey("chapterId") || ObjectUtil.isEmpty(jsonObject.get("chapterId"))) {
            return R.fail("章节ID不能为空！");
        }
        if (!jsonObject.containsKey("pixivType") || ObjectUtil.isEmpty(jsonObject.get("pixivType"))) {
            return R.fail("类型不能为空！");
        }
        if ("0".equals(jsonObject.get("pixivType"))) {
            NovelChapterVo vo = novelChapterService.queryById(jsonObject.getLong("chapterId"));
            NovelChapterBo bo = new NovelChapterBo();
            bo.setId(vo.getId());
            bo.setNovelId(vo.getNovelId());
            NovelChapterVo novelChapter = novelChapterService.selectLastChapterById(bo);
            if (novelChapter == null) {
                return R.fail("已到了第一章节");
            }
            result = getNovelChapter(novelChapter);
        } else {
            CaricatureChapterVo vo = caricatureChapterService.queryById(jsonObject.getLong("chapterId"));
            CaricatureChapterBo bo = new CaricatureChapterBo();
            bo.setId(vo.getId());
            bo.setCaricatureId(vo.getCaricatureId());
            CaricatureChapterVo caricatureChapter = caricatureChapterService.selectLastChapterById(bo);
            if (caricatureChapter == null) {
                return R.fail("已到了第一章节");
            }
            result = getCaricatureChapter(caricatureChapter);
        }
        return R.ok(result);
    }

    private Map<String, Object> getCaricatureChapter(CaricatureChapterVo caricatureChapterVo) {
        Map<String, Object> result = new HashMap<>();
        // 判断是否免费 收费类型（0-免费看、1-VIP可看、2-钻石观看）
        if ("1".equals(caricatureChapterVo.getChargeType())) {
            UserInfoVo userInfo = userInfoService.queryById(LoginHelper.getUserId());
            if ("1".equals(userInfo.getIsMember())) {
                throw new RuntimeException("请开通会员再来阅读");
            }
        }
        if ("2".equals(caricatureChapterVo.getChargeType())) {
            BuyOrder buyOrder = buyOrderService.queryByProductId(caricatureChapterVo.getCaricatureId(), caricatureChapterVo.getId(), "3");
            if (ObjectUtil.isNull(buyOrder)) {
                throw new RuntimeException("请购买此章节再来阅读");
            }
        }

        // 更新热度量和当前观看章节
        CaricatureInfoBo caricatureInfoBo = new CaricatureInfoBo();
        caricatureInfoBo.setId(caricatureChapterVo.getCaricatureId());
        caricatureInfoBo.setCurrentChapter(String.valueOf(caricatureChapterVo.getId()));
        caricatureInfoService.updateCaricatureChapterAndHeatNum(caricatureInfoBo);

        result.put("chapterId", caricatureChapterVo.getId());
        result.put("caricatureId", caricatureChapterVo.getCaricatureId());
        result.put("chapterContent", caricatureChapterVo.getChapterUrl());
        result.put("chapterTitle", caricatureChapterVo.getChapterTitle());
        result.put("chargeType", caricatureChapterVo.getChargeType());
        result.put("consumeDiamond", caricatureChapterVo.getConsumeDiamond());
        return result;
    }

    private Map<String, Object> getNovelChapter(NovelChapterVo novelChapterVo) {
        Map<String, Object> result = new HashMap<>();
        // 判断是否免费 收费类型（0-免费看、1-VIP可看、2-钻石观看）
        if ("1".equals(novelChapterVo.getChargeType())) {
            UserInfoVo userInfo = userInfoService.queryById(LoginHelper.getUserId());
            if ("1".equals(userInfo.getIsMember())) {
                throw new RuntimeException("请开通会员再来阅读");
            }
        }
        if ("2".equals(novelChapterVo.getChargeType())) {
            BuyOrder buyOrder = buyOrderService.queryByProductId(novelChapterVo.getNovelId(), novelChapterVo.getId(), "2");
            if (ObjectUtil.isNull(buyOrder)) {
                throw new RuntimeException("请购买此章节再来阅读");
            }
        }

        // 更新热度量和当前观看章节
        NovelInfoBo novelInfoBo = new NovelInfoBo();
        novelInfoBo.setId(novelChapterVo.getNovelId());
        novelInfoBo.setCurrentChapter(String.valueOf(novelChapterVo.getId()));
        novelInfoService.updateNovelChapterAndHeatNum(novelInfoBo);

        result.put("chapterId", novelChapterVo.getId());
        result.put("novelId", novelChapterVo.getNovelId());
        result.put("chapterContent", novelChapterVo.getChapterContent());
        result.put("chapterTitle", novelChapterVo.getChapterTitle());
        result.put("chargeType", novelChapterVo.getChargeType());
        result.put("consumeDiamond", novelChapterVo.getConsumeDiamond());
        return result;
    }


}
